package com.wehealth;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;
import android.support.v4.app.Fragment;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;

import com.umeng.analytics.MobclickAgent;
import com.wehealth.Dr_List;
import com.wehealth.Dr_Free;
import com.wehealth.adapter.Adapter_Health_search_food_item;
import com.wehealth.adapter.Adapter_Health_search_item;
import com.wehealth.adapter.Adapter_QuestionList;
import com.wehealth.dm.DM_HealthSearchFoodAndSportClassify;
import com.wehealth.dm.DM_HealthSearchFoodInfo;
import com.wehealth.dm.DM_HealthSearchList;
import com.wehealth.dm.DM_HealthSearchSportInfo;
import com.wehealth.dm.DM_PlanDay_new;
import com.wehealth.dm.QuestionData;
import com.wehealth.util.GetUrl;

@SuppressLint("ValidFragment")
public class plan_day_info_sport_descrip extends Fragment {
	
	private MainActivity context;


	private static  String JSONResult;
	private static final int NET_ERROR = -100;
	private String  mSportID;
	private String ID;
	private DM_HealthSearchSportInfo mSportInfo;

	
	private TextView  nameTv;
	private TextView  energyTv;
	private TextView  levelTv;
	private TextView  suitTV;
	private TextView  timeTv;
	private TextView descript_sport;
	private boolean isCompleted =false;
	private int weekday;
	private String mRemindTimeNew;
	
	private CheckBox  mRemindCB;
	private String state ="0";
	private TextView mRemindTime;
	private ImageButton mRemindTimeSet;
	private DM_PlanDay_new mPlan;
	private AlertDialog mDialog;
	
	public  plan_day_info_sport_descrip( )
	{
	
	}
	
	public plan_day_info_sport_descrip(DM_PlanDay_new item,int weekday){
		mPlan = item;
		mSportID = mPlan.getcontentIDs();
		this.ID =mPlan.getID();
		state = mPlan.getisCompleted();
		if(state.equals("0")){
			isCompleted =false;
		}else{
			isCompleted =true;
		}
		this.weekday = weekday;
	}

	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		return  inflater.inflate(R.layout.plan_day_info_sport_descrip, null);
	}
	
	public void onActivityCreated(Bundle savedInstanceState){
		
		super.onActivityCreated(savedInstanceState);
		
		
		MainActivity activity = (MainActivity)getActivity();
		context = activity;
		mSportInfo = new DM_HealthSearchSportInfo();
	
		nameTv = (TextView)context.findViewById(R.id.sport_name);
		energyTv = (TextView)context.findViewById(R.id.sport_energy);
		levelTv = (TextView)context.findViewById(R.id.sport_level_tv);
		timeTv = (TextView)context.findViewById(R.id.sport_time);
		descript_sport = (TextView)context.findViewById(R.id.sport_instruct);
		
		ConnService();

		TextView title=(TextView)activity.findViewById(R.id.header_title);
		String titlename = activity.getString(R.string.play_day_info);
		title.setText(titlename);
		Button bBack = (Button) activity.findViewById(R.id.header_bBack);
	    bBack.setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{
					context.switchContentHome();
				}
			});
	    
	    
	    TextView mDoFlag =(TextView)activity.findViewById(R.id.sport_do_flag);
	    mDoFlag.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String result =null;
				if(isCompleted){
					 result = getString(R.string.play_day_info_do_flag_fail);
					 context.openDialogTitle("提示",result,"确定");
				}else{
					final Calendar c = Calendar.getInstance(); 
					 String mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));  
					int mWayValue = Integer.valueOf(mWay);
					Log.d("SIMMON","  mWayValue="+mWayValue);
					Log.d("SIMMON","  weekday="+weekday);
					if(mWayValue==1){
						mWayValue = 8;
					}
					if((mWayValue-1)==weekday){
						connectServierDoFlagData();
					}else{
						result = getString(R.string.play_day_info_do_flag_error_time);
						context.openDialogTitle("提示",result,"确定");
					}
				}
			}
		});
	    
	    
		mRemindCB =(CheckBox)activity.findViewById(R.id.remind_time_cb);
		mRemindCB.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean stateB) {
				// TODO Auto-generated method stub
				Log.d("SIMMON","stateB="+stateB);
				 if(stateB){
					 state ="1";
				 }else{
					 state ="0";
				 }
				 connectServierUpdateData();
				
			}
		});
		
		mRemindTime =(TextView)activity.findViewById(R.id.remind_time_tv);
		String time =mPlan.getTime();
		mRemindTime.setText(time);
		
		mRemindTimeSet =(ImageButton)activity.findViewById(R.id.remind_time_bt);
		mRemindTimeSet.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				 openSetTimeDialog();
			}
		});
	    
	    
	    
		 
	}
	
	

    private void  ConnService(){
        
        //读取接口数据
        new Thread(){
            @Override
            public void run(){
            //你要执行的方法
                try {
                    InitThisView();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
 
    			Message msg = new Message();
    			msg.what =0;
    			handler.sendMessage(msg);
            }
            }.start();
    }
    
	private void connectServierUpdateData(){
		
		new Thread(){
			@Override
			public void run(){
				try {
					UpdateRemindState();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Message msg = new Message();
				msg.what =1;
				handler.sendMessage(msg);
			}
		}.start();
	}
    
	private void connectServierDoFlagData(){
		
		new Thread(){
			@Override
			public void run(){
				try {
					doFlagForInfo();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			Message msg = new Message();
			msg.what =4;
			handler.sendMessage(msg);
			}
		}.start();
	}
    
	
	
	private void  doFlagForInfo() throws IOException
	{

		String httpUrl = com.wehealth.util.GetUrl.Plan_CompleteItem_URL();
		 HttpPost httpRequest= new HttpPost(httpUrl);
		 
		 List <NameValuePair> params = new ArrayList <NameValuePair>();
		 params.add(new BasicNameValuePair("ID",ID));
		 try
		 {
			 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
			 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest); 
			 if(httpResponse.getStatusLine().getStatusCode() == 200)
			 {
				 JSONResult = EntityUtils.toString(httpResponse.getEntity());
				 Log.d("SIMMON","  JSONResult= "+JSONResult);
			 }
		 }
		 catch(Exception e)
		 {
			
			 Log.e("error:",  e.toString());
			 
		 }

	}
	
	   private void UpdateDoFlagView(String strJSON){
	       try{
	                JSONObject jsonObject = new JSONObject(strJSON); 
	                String  result =   jsonObject.getString("result");
	               if(result.equals("1")){
						    String dialog = getString(R.string.play_day_info_do_flag_sucess);
							context.openDialog(dialog,"好的");
	               }else{
	            	   context.openDialogBt(NET_ERROR); 
	               }
	            }
	            catch(JSONException ex)
	            {
	                    Log.e("JSON Error: ", ex.toString()); 
	            }
	    }
	
	   
		private void  UpdateRemindState() throws IOException
		{

			String httpUrl = com.wehealth.util.GetUrl.Plan_UpdateRemindState_URL();
			 HttpPost httpRequest= new HttpPost(httpUrl);
			 
			 List <NameValuePair> params = new ArrayList <NameValuePair>();
			 Log.d("SIMMON","  itemID= "+ID);
			 params.add(new BasicNameValuePair("id",ID));
			 params.add(new BasicNameValuePair("state",state));
			 
			 try
			 {
				 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
				
				 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
				 
				 if(httpResponse.getStatusLine().getStatusCode() == 200)
				 {
					 JSONResult = EntityUtils.toString(httpResponse.getEntity());
					 Log.d("SIMMON","Plan_Day2  JSONResult="+JSONResult);
				 }
			 }
			 catch(Exception e)
			 {
				
				 Log.e("error:",  e.toString());
				 
			 }

		}
		
		   private void UpdateRemind(String strJSON){
		       try{
		                JSONObject jsonObject = new JSONObject(strJSON); 
		                String  result =   jsonObject.getString("result");
		               if(result.equals("1")){
		            	    updateCheckBoxState();
		               }else{
		            	   context.openDialogBt(NET_ERROR); 
		               }
		            }
		            catch(JSONException ex)
		            {
		                    Log.e("JSON Error: ", ex.toString()); 
		            }
		    }
	
    private void  InitThisView() throws IOException
    {
         String urlAPI = GetUrl.GetHealthSearch_SportInfo_Url();
         HttpPost httpRequest= new HttpPost(urlAPI);
         List <NameValuePair> params = new ArrayList <NameValuePair>();

         params.add(new BasicNameValuePair("ID",mSportID));
         try
         {
             httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
             HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);       
             if(httpResponse.getStatusLine().getStatusCode() == 200)
             {  
                 JSONResult = EntityUtils.toString(httpResponse.getEntity()); 
             }       
         }
         catch(Exception e)
         {      
            
         }

    }
    
    
    
    //定义Handler对象
    private Handler handler =new Handler(){
        @Override
        public void handleMessage(Message msg){
        super.handleMessage(msg);
        //处理UI
	        if(JSONResult ==null){
	            openDialog(NET_ERROR);
	        }else{
	        	switch (msg.what) {
				case 0:
				    BindList(JSONResult);
					break;
				case 1:
					UpdateRemind(JSONResult);
					break;
				case 2:
					UpdateRemindTime(JSONResult);
					break;
				case 4:
					UpdateDoFlagView(JSONResult);
					break;
	        	}
	            JSONResult =null;
	        }
        }
    };
    

    
    //将JSON数据绑定到LISTVIEW
    private void BindList(String strJSON){
       try{
                JSONObject jsonObject = new JSONObject(strJSON); 
                JSONArray  aNews =  new JSONArray( jsonObject.getString("result") );  
                for(int i=0; i<aNews.length(); i++)
                    {
                	mSportInfo.setName(aNews.getJSONObject(i).getString("name"));
                	mSportInfo.setEnergy(aNews.getJSONObject(i).getString("energy"));
                	mSportInfo.settime(aNews.getJSONObject(i).getString("time"));
                	String  level =aNews.getJSONObject(i).getString("level");
                	mSportInfo.setlevel(level);
                	String  suit =aNews.getJSONObject(i).getString("suit");
                	mSportInfo.setsuit(suit);
                  String descript = aNews.getJSONObject(i).getString("description");
                  mSportInfo.setDescription(descript);
                }
                updateViewData(mSportInfo);
            }
            catch(JSONException ex)
            {
                    Log.e("JSON Error: ", ex.toString()); 
            }
    }
    
    
    private  void updateViewData(DM_HealthSearchSportInfo data){
		nameTv.setText(data.getName());
		String energyValue = data.getEnergy()+getString(R.string.health_search_sport_descript_energy);
		energyTv.setText(energyValue);
		levelTv.setText(data.getlevel());
		String time = data.gettime()+getString(R.string.health_search_sport_descript_time);
		timeTv.setText(time);
		descript_sport.setText(data.getDescription());
    	
    }
    
    
    
    private void openDialog(final int result){
        context.openDialogBt(result);
     }  
    
    private void updateCheckBoxState(){
    	if(state.equals("1")){
    		mRemindCB.setChecked(true);
    	}else{
    		mRemindCB.setChecked(false);
    	}	
    }
    
    
    private void openSetTimeDialog(){
	    AlertDialog.Builder builder = new AlertDialog.Builder(context);  
	    View view = View.inflate(context, R.layout.set_time_dialog, null);
	    final TimePicker timePicker =
	            (android.widget.TimePicker) view.findViewById(R.id.time_picker); 
	    builder.setView(view);  
	    Calendar cal = Calendar.getInstance(); 
	    cal.setTimeInMillis(System.currentTimeMillis());  
	    
	    timePicker.setIs24HourView(true);  
	    timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY));  
	    timePicker.setCurrentMinute(Calendar.MINUTE); 

	    
	    TextView leftBt =(TextView)view.findViewById(R.id.dialog_self_left_bt);
	    leftBt.setText("取消");
	    leftBt.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				mDialog.cancel();
			}
		});
	    
	    TextView rightBt =(TextView)view.findViewById(R.id.dialog_self_right_bt);
	    rightBt.setText("确定");
	    rightBt.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
                StringBuffer sb = new StringBuffer();
                sb.append(timePicker.getCurrentHour()) 
                .append(":").append(timePicker.getCurrentMinute());
                mRemindTimeNew = sb.toString();
				connectServierUpdateRemindTime();
				mDialog.dismiss();
			}
		});
	    

	    mDialog =builder.create();  
	    mDialog.show();
	}
	
    
	private void connectServierUpdateRemindTime(){
		
		new Thread(){
			@Override
			public void run(){
				try {
					UpdateRemindTime();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Message msg = new Message();
				msg.what =2;
				handler.sendMessage(msg);
			}
		}.start();
	}
	
	private void  UpdateRemindTime() throws IOException
	{

		String httpUrl = com.wehealth.util.GetUrl.Plan_UpdateRemindTime_URL();
		 HttpPost httpRequest= new HttpPost(httpUrl);
		 
		 List <NameValuePair> params = new ArrayList <NameValuePair>();
		 params.add(new BasicNameValuePair("id",ID));
		 params.add(new BasicNameValuePair("time",mRemindTimeNew));
		 
		 try
		 {
			 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
			
			 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
			 
			 if(httpResponse.getStatusLine().getStatusCode() == 200)
			 {
				 JSONResult = EntityUtils.toString(httpResponse.getEntity());
				 Log.d("SIMMON","  JSONResult= "+JSONResult);
			 }
		 }
		 catch(Exception e)
		 {
			
			 Log.e("error:",  e.toString());
			 
		 }

	}
	
	   private void UpdateRemindTime(String strJSON){
	       try{
	                JSONObject jsonObject = new JSONObject(strJSON); 
	                String  result =   jsonObject.getString("result");
	               if(result.equals("1")){
	            	   updateRemindTimeView();
	               }else{
	            	   context.openDialogBt(NET_ERROR); 
	               }
	            }
	            catch(JSONException ex)
	            {
	                    Log.e("JSON Error: ", ex.toString()); 
	            }
	    }
	   
	    private void updateRemindTimeView(){
	    	mRemindTime.setText(mRemindTimeNew);
	    }
    
}
